import type { Verse, VersesData } from '../types/verses'

// 动态导入verses数据
let versesCache: VersesData | null = null

export async function getVersesData(): Promise<VersesData> {
  if (versesCache) {
    return versesCache
  }
  
  try {
    const versesModule = await import('../data/verses.json')
    const data = versesModule.default || versesModule
    
    // 确保数据结构正确
    if (data && typeof data === 'object' && 'verses' in data) {
      versesCache = data as VersesData
      return versesCache
    } else if (Array.isArray(data)) {
      // 如果直接是数组，包装成正确的结构
      versesCache = { verses: data as Verse[] }
      return versesCache
    } else {
      throw new Error('Invalid data structure')
    }
  } catch (error) {
    console.error('Failed to load verses data:', error)
    // 返回空数据作为后备
    return { verses: [] }
  }
}

export function getTodayVerse(verses: Verse[]): Verse | null {
  if (verses.length === 0) return null
  
  const today = new Date()
  const dayOfYear = Math.floor((today.getTime() - new Date(today.getFullYear(), 0, 0).getTime()) / 86400000)
  return verses[dayOfYear % verses.length]
}

export function getRandomVerse(verses: Verse[]): Verse | null {
  if (verses.length === 0) return null
  
  const randomIndex = Math.floor(Math.random() * verses.length)
  return verses[randomIndex]
}